package com.studay;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml.Encoding;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.database.EducationPad.EducationColumns;
import com.studay.bean.ChannelInfo;
import com.studay.bean.ChannelPojo;
import com.studay.bean.Const;
import com.studay.bean.Course;
import com.studay.bean.DianBoPojo;
import com.util.LogManager;
import com.xml.ChannelHandler;
import com.xml.DiaoBoHandler;

public class IndexActivity extends Activity {
	private ListView videoList;
	private List<Map<String, String>> video;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.index);

		videoList = (ListView) findViewById(R.id.videoList);
		video = new ArrayList<Map<String, String>>();

		View view = findViewById(R.id.titleLayout);
		view.getBackground().setAlpha(120);

		View mainLayout = findViewById(R.id.mainLayout);
		mainLayout.getBackground().setAlpha(180);

		Bundle bundle = this.getIntent().getExtras();
		String channelUrl = bundle.getString("ChannelUrl");

		LogManager.LogShow(Const.TAG, "访问频道列表地址：" + channelUrl,
				LogManager.INFO);
		URL url;
		try {
			url = new URL(channelUrl);
			InputStream in = url.openConnection().getInputStream();
			ChannelHandler xmlHandler = new ChannelHandler();
			android.util.Xml.parse(in, Encoding.UTF_8, xmlHandler);
			List<ChannelPojo> list = xmlHandler.getList();

			for (ChannelPojo xp : list) {
				boolean flag = true;// true - not use db , false - use db
				Map<String, String> map = new HashMap<String, String>();
				// contrast version
				Cursor c = getContentResolver()
						.query(
								EducationColumns.CHANNEL_URI,
								new String[] { "id", EducationColumns.VERSION,
										EducationColumns.PROTOCL,
										EducationColumns.FISSERVERURL,
										EducationColumns.NODES },
								"groupNum=? AND xmlUrl=?",
								new String[] { Const.result.getGroup(),
										xp.getXmlurl() },
								EducationColumns.DEFAULT_SORT_ORDER);
				// not null
				if (c.moveToFirst()) {
					map.put("id", "" + c.getInt(c.getColumnIndex("id")));
					if (xp.getVersion().equals(
							c.getString(c
									.getColumnIndex(EducationColumns.VERSION)))) {
						map.put(EducationColumns.PROTOCL, c.getString(c
								.getColumnIndex(EducationColumns.PROTOCL)));
						map
								.put(
										EducationColumns.FISSERVERURL,
										c
												.getString(c
														.getColumnIndex(EducationColumns.FISSERVERURL)));
						map.put(EducationColumns.NODES, c.getString(c
								.getColumnIndex(EducationColumns.NODES)));
						flag = false;// use db
					} else {// update
						LogManager.LogShow(Const.TAG, "update channel info",
								LogManager.INFO);
						ContentValues values = new ContentValues();
						values.put(EducationColumns.VERSION, xp.getVersion());
						values.put(EducationColumns.XMLURL, xp.getXmlurl());
						values.put(EducationColumns.GROUPNUM, Const.result
								.getGroup());
						getContentResolver().update(
								EducationColumns.CHANNEL_URI,
								values,
								"groupNum=? AND xmlUrl=?",
								new String[] { Const.result.getGroup(),
										xp.getXmlurl() });

						getContentResolver().delete(
								EducationColumns.PROJECT_URI,
								"channelId=?",
								new String[] { ""
										+ c.getInt(c.getColumnIndex("id")) });
					}
				} else {
					LogManager.LogShow(Const.TAG, "add channel info",
							LogManager.INFO);
					/* add channel info */
					ContentValues values = new ContentValues();
					values.put(EducationColumns.VERSION, xp.getVersion());
					values.put(EducationColumns.XMLURL, xp.getXmlurl());
					values.put(EducationColumns.GROUPNUM, Const.result
							.getGroup());
					getContentResolver().insert(EducationColumns.CHANNEL_URI,
							values);

					Cursor cid = getContentResolver().query(
							EducationColumns.CHANNEL_URI,
							new String[] { "id" },
							"groupNum=? AND xmlUrl=?",
							new String[] { Const.result.getGroup(),
									xp.getXmlurl() }, null);
					if (cid.moveToFirst()) {
						map
								.put("id", ""
										+ cid.getInt(cid.getColumnIndex("id")));
					}
				}
				map.put("data", xp.getChannelname());
				map.put("url", xp.getXmlurl());
				map.put("state", xp.getState());
				map.put("xmlfilename", xp.getXmlfilename());
				map.put("flag", "" + flag);
				video.add(map);
			}
		} catch (MalformedURLException e) {
			LogManager.LogShow(Const.TAG, e.getMessage(),
					LogManager.INFO);
		} catch (IOException e) {
			LogManager.LogShow(Const.TAG, e.getMessage(),
					LogManager.INFO);
		} catch (SAXException e) {
			LogManager.LogShow(Const.TAG, e.getMessage(),
					LogManager.INFO);
		}

		SimpleAdapter mySimpleAdapter = new SimpleAdapter(this,
				video,// 数据源
				R.layout.listviewtext,// ListView内部数据展示形式的布局文件listitem.xml
				new String[] { "data", "url", "state", "xmlfilename", "flag",
						EducationColumns.PROTOCL,
						EducationColumns.FISSERVERURL, EducationColumns.NODES },// HashMap中的两个key值
				new int[] { R.id.listViewtext1 });

		videoList.setAdapter(mySimpleAdapter);
		videoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				URL url = null;
				InputStream in = null;
				HashMap<String, String> map = (HashMap<String, String>) videoList
						.getItemAtPosition(arg2);
				Log.i(Const.TAG, "video state:" + map.get("state")
						+ " update state:" + map.get("flag"));
				if (map.get("state").equals("1")) {
					try {
						ChannelInfo channelInfo = new ChannelInfo();
						ArrayList<DianBoPojo> list = new ArrayList<DianBoPojo>();
						boolean flag = true;// true - not use db , false - use
											// db

						if (map.get("flag").equals("false")) {
							Log.i(Const.TAG, "get project list from db");
							Cursor c = getContentResolver().query(
									EducationColumns.PROJECT_URI, null,
									"channelId=?",
									new String[] { map.get("id") }, null);
							while (c.moveToNext()) {
								DianBoPojo project = new DianBoPojo();
								project.setCredit(c.getInt(c
										.getColumnIndex("credit")));
								project.setName(c.getString(c
										.getColumnIndex("name")));
								project.setRemark(c.getString(c
										.getColumnIndex("remark")));
								project.setPid(c
										.getInt(c.getColumnIndex("pid")));

								// get course List
								Cursor courseC = getContentResolver().query(
										EducationColumns.COURSE_URI, null,
										"pid=?",
										new String[] { "" + project.getPid() },
										null);
								ArrayList<Course> courseList = new ArrayList<Course>();
								while (courseC.moveToNext()) {
									Course course = new Course();
									course
											.setFilehash(courseC
													.getString(courseC
															.getColumnIndex("filehash")));
									course.setName(courseC.getString(courseC
											.getColumnIndex("name")));
									course.setPlaylength(courseC.getInt(courseC
											.getColumnIndex("playlength")));
									course.setProject(courseC.getString(courseC
											.getColumnIndex("project")));
									course.setTeacher(courseC.getString(courseC
											.getColumnIndex("teacher")));
									course
											.setTeacherInfo(courseC
													.getString(courseC
															.getColumnIndex("teacherInfo")));
									courseList.add(course);
								}
								project.setChildList(courseList);
								list.add(project);
							}

							channelInfo.setFisserverurl(map
									.get(EducationColumns.FISSERVERURL));
							channelInfo.setNodes(map
									.get(EducationColumns.NODES));
							channelInfo.setProtocl(map
									.get(EducationColumns.PROTOCL));

							flag = false;
						} else {
							url = new URL(map.get("url"));
							in = url.openConnection().getInputStream();
							// in = getAssets().open(map.get("url"));
							DiaoBoHandler xmlHandler = new DiaoBoHandler();
							android.util.Xml.parse(in, Encoding.UTF_8,
									xmlHandler);
							list = xmlHandler.getList();

							channelInfo = xmlHandler.getChannelInfo();

							Log.i(Const.TAG,
									"update channel info about channelInfo");
							ContentValues values = new ContentValues();
							values.put(EducationColumns.PROTOCL, channelInfo
									.getProtocl().toLowerCase());
							values.put(EducationColumns.FISSERVERURL,
									channelInfo.getFisserverurl());
							values.put(EducationColumns.NODES, channelInfo
									.getNodes());
							getContentResolver().update(
									EducationColumns.CHANNEL_URI,
									values,
									"groupNum=? AND xmlUrl=?",
									new String[] { Const.result.getGroup(),
											map.get("url") });

							Log.i(Const.TAG, "add project");
							for (DianBoPojo dbp : list) {
								ContentValues project = new ContentValues();
								project.put("name", dbp.getName());
								project.put("channelId", map.get("id"));
								project.put("remark", dbp.getRemark());
								project.put("credit", dbp.getCredit());
								getContentResolver().insert(
										EducationColumns.PROJECT_URI, project);

								Cursor c = getContentResolver().query(
										EducationColumns.PROJECT_URI,
										new String[] { "pid" },
										"name=? and channelId=? and credit=?",
										new String[] { dbp.getName(),
												map.get("id"),
												"" + dbp.getCredit() }, null);
								if (c.moveToFirst()) {
									List<Course> courseList = dbp
											.getChildList();
									// add course
									for (Course course : courseList) {
										ContentValues cValues = new ContentValues();
										cValues.put("name", course.getName());
										cValues.put("filehash", course
												.getFilehash());
										cValues.put("teacher", course
												.getTeacher());
										cValues.put("playlength", course
												.getPlaylength());
										cValues.put("teacherInfo", course
												.getTeacherInfo());
										cValues.put("project", course
												.getProject());
										cValues.put("pid", c.getInt(c
												.getColumnIndex("pid")));
										getContentResolver().insert(
												EducationColumns.COURSE_URI,
												cValues);
									}
								}
							}
							map.put("flag", "false");
						}

						Log.i(Const.TAG, "获得的项目数:" + list.size());
						Intent intent = new Intent(getApplicationContext(),
								ProjectActivity.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable("channelInfo", channelInfo);
						bundle.putParcelableArrayList("list", list);
						bundle.putString("projectName", map.get("data")
								.toString());
						bundle.putString("flag", "" + flag);
						intent.putExtras(bundle);
						startActivity(intent);
					} catch (IOException e) {
						Log.e(Const.TAG, e.getMessage());
					} catch (SAXException e) {
						Log.e(Const.TAG, e.getMessage());
					} finally {
						try {
							if (in != null) {
								in.close();
							}
						} catch (IOException e) {
						}
					}
				} else {
					Log.i(Const.TAG, "直播源"
							+ map.get("url").toLowerCase().trim() + "/"
							+ map.get("xmlfilename").trim());
					Intent intent = new Intent();
					Bundle bundle = new Bundle();
					bundle.putString("fileName", map.get("url").toLowerCase()
							.trim()
							+ "/" + map.get("xmlfilename").trim());
					intent.setClass(getApplicationContext(),
							FlashActivity.class);
					intent.putExtra("videoBundle", bundle);
					startActivity(intent);
				}
			}
		});
	}
}